package com.webchat.ugc.service.chain;

import com.webchat.common.bean.APIResponseBean;
import com.webchat.common.bean.APIResponseBeanUtil;
import com.webchat.common.enums.PromptTemplateEnum;
import com.webchat.common.service.FreeMarkEngineService;
import com.webchat.common.util.JsonUtil;
import com.webchat.domain.dto.aigc.ChatCompletionMessageRequest;
import com.webchat.domain.vo.response.moment.MomentVO;
import com.webchat.rmi.aigc.LLMChatClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;


@Slf4j
@Component
public class MomentReviewHandler implements MomentPublishHandler {


    @Autowired
    private FreeMarkEngineService freeMarkEngineService;

    @Autowired
    private LLMChatClient llmChatClient;

    @Override
    public void handle(MomentVO moment, MomentPublishHandlerChain chain) {

        // 这里我们仅支持对正文内容的审核
        String content = moment.getContent();
        if (StringUtils.isBlank(content)) {
            chain.handle(moment, chain);
            return;
        }

        String templateName = PromptTemplateEnum.MOMENT_REVIEW.getPath();
        Map<String, Object> vars = new HashMap<>();
        // TODO
        vars.put("author", "程序员七七");
        vars.put("input", content);
        String prompt;
        try {
            prompt = freeMarkEngineService.getContentByTemplate(templateName, vars);
        } catch (Exception e) {
            log.error("[朋友圈内容审核异常] ===> prompt模版引擎模版渲染失败！vars:{}",
                    JsonUtil.toJsonString(vars), e);
            chain.handle(moment, chain);
            return;
        }
        ChatCompletionMessageRequest chatCompletionMessage = new ChatCompletionMessageRequest(prompt);
        APIResponseBean<String> reviewResponse = llmChatClient.chat(chatCompletionMessage);
        Integer reviewScore = null;
        if (APIResponseBeanUtil.isOk(reviewResponse)) {
            String response = reviewResponse.getData();
            reviewScore = StringUtils.isNoneBlank(response) ? Integer.valueOf(response) : null;
        } else {
            log.error("[朋友圈内容审核异常] ===> LLM Chat Error！prompt:{}", prompt);
            chain.handle(moment, chain);
            return;
        }

        log.info("[朋友圈内容审核结果] ===> prompt:{}, 内容质量分:{}", prompt, reviewScore);

        moment.setReviewScore(reviewScore);
        chain.handle(moment, chain);
    }
}
